package com.vise.baseble.utils;

public class DataPacketUtil {
    public static byte[] packetWithData(byte[] data) {
        int length = data.length;
        if (length == 0) {
            return null;
        }

        byte[] c_data = new byte[length+7];
        c_data[0] = 0x3a;
        c_data[1] = (byte) (length >> 8);
        c_data[2] = (byte) (length & 0xff);

        long sum = 0;
        for (int i = 0; i < length; i++) {
            byte b = data[i];
            c_data[i + 3] = b;
            sum += b;
        }

        c_data[length + 3] = (byte) (sum >> 8);
        c_data[length + 4] = (byte) (sum & 0xff);
        c_data[length + 5] = 0x0d;
        c_data[length + 6] = 0x0a;
        return c_data;
    }

    public static boolean isValidPacketData(byte[] packetData) {
        int length = (int)packetData.length;
        if (length <= 7) {
            return false;
        }

        if (packetData[0] == 0x3a && packetData[length - 1] == 0x0a && packetData[length - 2] == 0x0d) {
            return true;
        } else {
            return false;
        }
    }

    public static byte[] dataWithPacketData(byte[] packetData) {
        int length = (int)packetData.length;
        if (isValidPacketData(packetData)) {
            byte[] data = new byte[length - 7];
            System.arraycopy(packetData, 3, data, 0, length-7);
            return data;
        }
        return null;
    }
}
